<template>
  <div class="app-container">
    <div>
      <el-table
        v-loading="listLoading"
        :data="attendList"
        :summary-method="getSummaries"
        class="el-table"
        element-loading-text="数据加载中，请稍后"
        show-summary
        height="85vh"
        sum-text="合计"
        border
        fit
        stripe
        highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByDir"
          :filter-method="filterNameHandler"
          :filters="attendFilter"
          column-key="name"
          sortable
          label="姓名"
          prop="name"
          width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column
          :sort-method="sortByDir"
          :filter-method="filterDepartNameHandler"
          :filters="departFilter"
          column-key="departName"
          sortable
          label="部门"
          prop="departName"
          width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.department.name }}
          </template>
        </el-table-column>

        <el-table-column label="迟到（分钟）" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.late !== 0">
              <el-tag type="danger">{{ scope.row.late }}</el-tag>
            </span>
            <span v-else>
              0
            </span>
          </template>
        </el-table-column>
        <el-table-column label="早退（分钟）" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.leaveEarly !== 0">
              <el-tag type="danger">{{ scope.row.leaveEarly }}</el-tag>
            </span>
            <span v-else>
              0
            </span>
          </template>
        </el-table-column>

        <el-table-column :sort-method="sortByAge" label="病假" align="center" show-overflow-tooltip width="150" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.illAbsence">
              <el-tag type="warning">是</el-tag>
            </span>
            <span v-else>
              否
            </span>
          </template>
        </el-table-column>
        <el-table-column :sort-method="sortByAge" label="事假" align="center" show-overflow-tooltip width="150" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.thingAbsence">
              <el-tag type="warning">是</el-tag>
            </span>
            <span v-else>
              否
            </span>
          </template>
        </el-table-column>
        <el-table-column :sort-method="sortByAge" label="公休" align="center" show-overflow-tooltip width="150" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.pubHoliday">
              <el-tag type="primary">是</el-tag>
            </span>
            <span v-else>
              否
            </span>
          </template>
        </el-table-column>

        <el-table-column
          :filter-method="filterDateHandler"
          :filters="[{'text':'今天','value': '0'},{'text':'最近三天','value': '3'},{'text':'最近一周','value': '7'},{'text':'最近30天','value': '30'},{'text':'最近90天','value': '90'}]"
          :filter-multiple="false"
          column-key="date"
          align="center"
          prop="created_at"
          label="考勤时间"
          width="200"
          sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.date | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByTime"
          align="center"
          prop="created_at"
          label="上次更新时间"
          width="200"
          sortable>
          <template slot-scope="scope">
            <i class="el-icon-time"/>
            <span>{{ scope.row.gmtModified }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <!--            <el-button size="small" @click.native.prevent="modRow(scope.$index, exeList)">编辑</el-button>-->
            &nbsp;&nbsp;
            <el-button type="danger" size="small" @click.native.prevent="deleteRow(scope.$index, attendList)">移除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <div style="margin-top: 10px; text-align: left">
        <el-pagination
          :total="totalSize"
          :current-page.sync="currentPage"
          :pager-count="11"
          :page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          background
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="fetchAttendData"/>
      </div>
    </div>
  </div>
</template>

<script>/* eslint-disable indent */

import { getAttends, deleteAttend } from '../../../../api/attend'

export default {
  filters: {
    formatDate: function(val) {
      const dateFormat = function(date, format) {
        date = new Date(date)
        const o = {
          'M+': date.getMonth() + 1,
          'd+': date.getDate(),
          'H+': date.getHours(),
          'm+': date.getMinutes(),
          's+': date.getSeconds(),
          'q+': Math.floor((date.getMonth() + 3) / 3),
          'S': date.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (const k in o) {
          if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
          }
        }
        return format
      }
      return dateFormat(val, 'yyyy-MM-dd')
    }
  },
  data() {
    return {
      attendList: null,
      listLoading: true,
      attendFilter: [],
      departFilter: [],

      workStateOptions: [{
        value: 'WORKING',
        label: '在职'
      }, {
        value: 'RETIRE',
        label: '退休'
      }, {
        value: 'QUIT',
        label: '离职'
      }],

      // enableLimit: true,
      totalSize: 0,
      currentPage: 1,
      pageSize: 50
    }
  },
  created() {
    this.fetchAttendData()
  },
  methods: {

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchAttendData()
    },

    filterDateHandler(value, row, column) {
      const now = new Date()
      const nowDateStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)
      console.log(row.date)
      const t = new Date(row.date.toString())
      t.setHours(0)
      t.setMinutes(0)
      t.setSeconds(0)
      t.setMilliseconds(0)
      console.log(t)
      const div = Math.abs(parseInt(((nowDateStart.getTime() - t.getTime()) / 1000 / 3600 / 24)))
      return div <= Number(value)
    },

    filterNameHandler(value, row, column) {
      return row.employeeId === value
    },

    filterDepartNameHandler(value, row, column) {
      return row.department.departId === value
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (index === 2) {
            const values = data.map(item => Number(item.late))
            let totalMin = 0
            values.forEach(function(value) {
                totalMin += value
              }
            )
            sums[index] = totalMin + ' 分钟'
            return
          }

          if (index === 3) {
            const values = data.map(item => Number(item.leaveEarly))
            let totalMin = 0
            values.forEach(function(value) {
                totalMin += value
              }
            )
            sums[index] = totalMin + '分钟'
            return
          }

          if (index === 4) {
            const times = data.filter((v) => v.illAbsence === true).length
            sums[index] = times + '次'
            return
          }
          if (index === 5) {
            const times = data.filter((v) => v.thingAbsence === true).length
            sums[index] = times + '次'
            return
          }
          if (index === 6) {
            const times = data.filter((v) => v.pubHoliday === true).length
            sums[index] = times + '次'
            return
          }
          sums[index] = '无数据项统计'
        }
      )
      return sums
    },

    sortByDir(a, b) {
      return a.name.localeCompare(b.name)
    },
    sortBySort(a, b) {
      return a.sort - b.sort
    },
    sortByDepart(a, b) {
      return a.department.name.localeCompare(b.department.name)
    },
    sortBySex(a, b) {
      return a.sex.localeCompare(b.sex)
    },
    sortByGroupNum(a, b) {
      return a.numPerGrp - b.numPerGrp
    },
    sortByAge(a, b) {
      return a.age - b.age
    },
    sortByTime(a, b) {
      return new Date(a.gmtModified).getTime() - new Date(b.gmtModified).getTime()
    },
    modRow() {
      this.$message({
        message: '点击左侧箭头展开详细信息进行编辑',
        type: 'info'
      })
    },
    deleteRow(index, rows) {
      const that = this
      console.log(rows[index])
      deleteAttend(rows[index].id).then(response => {
        console.log(response)
        that.displayResult(response, '删除')
        if (response.success) {
          rows.splice(index, 1)
        }
      })
    },
    fetchAttendData() {
      const that = this
      this.listLoading = true
      getAttends(this.currentPage, this.pageSize, true).then(response => {
        const result = response.data
        this.attendList = result.data
        that.totalSize = result.totalSize

        if (this.attendList != null && this.attendList.length > 0) {
          const keySet = new Set()
          const newArr = []
          const keySet1 = new Set()
          const newArr1 = []
          this.attendList.forEach((employee) => {
            if (!keySet.has(employee.employeeId)) {
              keySet.add(employee.employeeId)
              newArr.push({
                'text': employee.name,
                'value': employee.employeeId
              })
            }

            if (!keySet1.has(employee.department.departId)) {
              keySet1.add(employee.department.departId)
              newArr1.push({
                'text': employee.department.name,
                'value': employee.department.departId
              })
            }
          })
          this.attendFilter = newArr
          this.departFilter = newArr1
        }
        this.listLoading = false
      })
    },
    displayResult(response, text) {
      if (!response.success) {
        this.$message({
          message: text + '出错！' + response.message,
          type: 'error'
        })
        return
      }
      this.$message({
        message: text + '成功!',
        type: 'success'
      })
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .expanded_input {
    width: 555px;
  }
</style>
